<template>
  <div class="create-order">
    <!--生成订单页面公用头部，这里需要提供一个callback方法，当单击返回按钮时，执行deletelocal方法，清理cartItemIds数据-->
    <custom-header :title="'生成订单'" @callback="deleteLocal"></custom-header>
    <div class="address-wrap">
      <!--收货地址，单击前往地址管理页面-->
      <div class="name" @click="goTo">
        <!--收货人名称-->
        <span>{{ address.userName }}</span>
        <!--收货人手机号码-->
        <span>{{ address.userPhone }}</span>
      </div>
      <!--详细地址-->
      <div class="address">
        {{ address.provinceName }} {{ address.cityName }} {{ address.regionName }} {{ address.detailAddress }}
      </div>
      <van-icon class="arrow" name="arrow" @click="goTo('/address')"/>
    </div>
    <!--商品展示部分-->
    <div class="good">
      <!--单项商品，通过cartList变量循环输出-->
      <div class="good-item" v-for="(item, index) in cartList" :key="index">
        <div class="good-img">
          <img :src="$filters.prefix(item.goodsCoverImg)" alt="">
        </div>
        <div class="good-desc">
          <div class="good-title">
            <span>{{ item.goodsName }}</span>
            <span>{{ item.goodsCount }}</span>
          </div>
          <div class="good-btn">
            <div class="price">￥{{ item.sellingPrice }}</div>
          </div>
        </div>
      </div>
    </div>
    <!--底部金额和生成订单按钮部分-->
    <div class="pay-wrap">
      <div class="price">
        <span>商品金额</span>
        <!--通过计算属性计算出商品总额-->
        <span>￥{{ total }}</span>
      </div>
      <!--单击生成订单按钮，调用handleCreateOrder方法，将地址id和购物车单项id作为参数传入，完成后把订单id赋值给orderNo，触发底部弹窗显示-->
      <van-button @click="handleCreateOrder" class="pay-btn" color="#1baeae" type="primary" block>生成订单</van-button>
    </div>
    <!--模拟支付宝和微信的付款弹窗-->
    <van-popup
      closeable
      :close-on-click-overlay="false"
      v-model:show="showPay"
      position="bottom"
      :style="{ height: '30%'}"
      @close="close"
    >
      <div :style="{ width: '90%', margin:'0 auto', padding: '50px 0'}">
        <van-button :style="{marginBottom: '10px'}" color="#1989fa" block @click="handlePayOrder(1)">支付宝支付</van-button>
        <van-button color="#4fc08d" block @click="handlePayOrder(2)">微信支付</van-button>
      </div>
    </van-popup>
  </div>
</template>
<script>
import { createOrder, payOrder } from '@/service/order'
import { getByCartItemIds } from 'service/cart'
import { reactive, onMounted, toRefs, computed } from 'vue'
import CustomHeader from 'components/CustomHeader.vue' //公用头部
import { getDefaultAddress, getAddressDetail } from 'service/address' //地址相关接口方法
import { setLocal } from 'utils/help' //工具方法
import { Toast } from 'vant'
import { useRoute, useRouter } from 'vue-router'
import { get } from 'vant/lib/utils'
import { getLocal } from 'utils/help' //引入工具库方法

export default {
  components: {
    CustomHeader //注册组件
  },
  setup() {
    const router = useRouter() //生成router实例
    const route = useRoute() //生成route实例
    const state = reactive({
      address: {}, //地址详情变量
      cartList: [], //选中的购物车商品
      showPay: false, //显示付款弹出层
      orderNo: '', //生成订单后的订单id
    })
    onMounted(() => {
      initData()
    })
    //初始化数据
    const initData = async() => {
      Toast.loading({message: '加载中...', forbidClick: true});
      //获取地址栏查询参数addressId, cartItemIds
      const { addressId, cartItemIds } = route.query 
      //在有addressId的情况下，说明是从地址管理页面选择的地址的，再返回来生成订单页面，此时需要调用getAddressDetail方法
      //在没有addressId的情况下，说明是从购物车页面进入的，直接通过getDefaultAddress方法获取默认地址
      console.log('addressId:',addressId)

      const {data: address } = addressId ? await getAddressDetail(addressId) : await getDefaultAddress()
      if(!address) {
        //当address对象没有值时，说明没有设置默认地址，需要默认前往address地址管理页面新建地址
        router.push({path: '/address'})
        return 
      }
      //如果有address对象，则赋值给state.address
      state.address = address 


      //判断cartItemIds是否有值，在没有值的情况下，前往localStorage获取
      const _cartItemIds = cartItemIds ? JSON.parse(cartItemIds) : JSON.parse(getLocal('cartItemIds'))
      //再次设置cartItemIds
      setLocal('cartItemIds', JSON.stringify(_cartItemIds))
      //通过getByCartItemIds接口获取购物车商品列表
      const {data:list} = await getByCartItemIds({cartItemIds:_cartItemIds.join(',')})

      //购物车商品列表
      state.cartList = list

      Toast.clear()
    }
    //手动单击，前往地址管理页面
    const goTo = () => {
      //需要在返回时带上cartItemIds参数
      router.push({path: '/address', query:{cartItemIds: JSON.stringify(state.cartItemIds), from: 'create-order'}})
    }
    //清理本地cartItemIds方法
    const deleteLocal = () => {
      setLocal('cartItemIds', '')
    }
    //生成订单方法
    const handleCreateOrder = async() => {
      const params = {
        addressId: state.address.addressId, //选择地址id
        cartItemIds: state.cartList.map(item => item.cartItemId) //购物车商品id
      }
      const { data } = await createOrder(params)
      setLocal('cartItemIds', '')
      state.orderNo = data
      state.showPay = true
    }
    //关闭弹窗后，直接跳转至个人订单中心，此时订单已经生成，但未付款
    const close = () => {
      router.push({path: '/order'})
    }
    //订单付款，模拟支付宝和微信付款界面
    const handlePayOrder =async(type) => {
      await payOrder({orderNo: state.orderNo, payType: type})
      Toast.success('支付成功')
      setTimeout(() => {
        router.push({path:'/order'})
      }, 2000)
    }
    //通过计算属性计算该笔订单的总额
    const total = computed(() => {
      let sum = 0
      state.cartList.forEach(item=>{
        sum += item.goodsCount * item.sellingPrice
      })
      return sum
    })
    //返回给template使用
    return {
      ...toRefs(state),
      goTo,
      deleteLocal,
      handleCreateOrder,
      handlePayOrder,
      close,
      total
    }
  }
}
</script>

<style lang="less" scoped>
@import '../theme/custom';
.create-order{
  background: #f9f9f9;
  .address-wrap {
    margin-bottom: 20px;
    background: #fff;
    position: relative;
    font-size: 14px;
    padding: 15px;
    color: #222333;
    .name, .address{
      margin: 10px 0;
    }
    .arrow{
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
      font-size: 20px;
    }
    &::before{
      position: absolute;
      right: 0;
      bottom: 0;
      left: 0;
      height: 2px;
      background: -webkit-repeating-linear-gradient(135deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
      background: repeating-linear-gradient(-45deg, #ff6c6c 0, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
      background-size: 80px;
      content: '';
    }
  }
  .good{
    margin-bottom: 120px;
  }
  .good-item{
    padding: 10px;
    background: #fff;
    display: flex;
    .good-img{
      img{
        .wh(100px, 100px)
      }
    }
    .good-desc{
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      flex: 1;
      padding: 20px;
      .good-title{
        display:flex;
        justify-content: space-between;
      }
      .good-btn{
        display:flex;
        justify-content: space-between;
        .price{
          font-size: 16px;
          color: red;
          line-height: 28px;
        }
        .van-icon-delete{
          font-size: 20px;
          margin-top: 4px;
        }
      }
    }
  }
  .pay-wrap{
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background: #fff;
    padding: 10px 0;
    padding-bottom: 50px;
    border-top: 1px solid #e9e9e9;
    >div{
      display: flex;
      justify-content: space-between;
      padding: 0 5%;
      margin: 10px 0;
      font-size: 14px;
      span:nth-child(2){
        color: red;
        font-size: 18px;
      }
    }
    .pay-btn{
      position: fixed;
      bottom: 7px;
      right: 0;
      left: 0;
      width: 90%;
      margin: 0 auto;
    }
  }
}
</style>